package cn.tedu.search.service

import java.util.ArrayList

import org.elasticsearch.client.transport.TransportClient
import org.elasticsearch.index.query.QueryBuilders
import org.springframework.stereotype.Service

import cn.tedu.common.pojo.Product
import cn.tedu.search.mapper.SearchMapper
import cn.tedu.staticResources.ComRe
import org.springframework.beans.factory.annotation.Autowired
import cn.tedu.common.utils.MapperUtil

@Service
class SearchService() {

  @Autowired
  private var searchMapper: SearchMapper = _

  @Autowired
  private var client: TransportClient = _

  def createIndex(indexName: String) {
    //数据源
    val pList = searchMapper.queryAll()
    try {
      //封装document数据,写入索引
      //创建一个索引
      val admin = client.admin.indices
      if (!admin.prepareExists(indexName).get.isExists) admin.prepareCreate(indexName).get
      //将pList写入到索引文件
      pList.forEach { product =>
        val jsonData = MapperUtil.MP.writeValueAsString(product)
        client.prepareIndex(indexName, ComRe.product, product.getProductId).setSource(jsonData).get
      }
    } catch {
      case e: Exception => e.printStackTrace()
    }

  }
  def search(text: String, page: Int, rows: Int) = {
    //构造一个查询条件
    val query = QueryBuilders.multiMatchQuery(text, "productName", "productCategory", "productDescription")
    //按照分页查询 start=(page-1)*rows
    val start = (page - 1) * rows
    val response = client.prepareSearch("emindex").setQuery(query).setFrom(start).setSize(rows).get
    val allHits = response.getHits //totalHits
    //maxScore
    System.out.println("总共查询:" + allHits.totalHits)
    val hits = allHits.getHits
    //循环数据之前准备一个返回的数据
    val pList: ArrayList[Product] = null

    hits.foreach { hit =>
      //获取hits中的sourcejson字符串,解析成product
      val jsonData = hit.getSourceAsString
      try {
        //解析json,转化product,封装product
        pList.add(MapperUtil.MP.readValue(jsonData, classOf[Product]))
      } catch {
        case e: Exception => e.printStackTrace()
      }
    }
    pList
  }
}